﻿using AutoMapper;
using MediatR;
using MyMES.Domain.yjb;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Writer.API.Application.Commends.settingCommand;
using MyMES.Writer.API.FileNlog;

namespace MyMES.Writer.API.Application.CommendHandlers.settingCommand
{
    public class AddTaskInfoCommandHandlers : IRequestHandler<AddTaskInfoCommand, APIResult<TaskInfo>>
    {
        private readonly IBaseRepository<TaskInfo> accreop;
        private readonly IMapper mapper;
        private readonly Nolgs nlogs;

        public AddTaskInfoCommandHandlers(IBaseRepository<TaskInfo> accreop, IMapper mapper, Nolgs nlogs)
        {
            this.accreop = accreop;
            this.mapper = mapper;
            this.nlogs = nlogs;
        }
        /// <summary>
        /// 任务添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<TaskInfo>> Handle(AddTaskInfoCommand request, CancellationToken cancellationToken)
        {
            var startTime = DateTime.Now;
            try
            {
                APIResult<TaskInfo> result = new APIResult<TaskInfo>();
                result.Code = APIEnum.添加成功;
                result.Msg = "添加成功";
                var model = mapper.Map<TaskInfo>(request);
                string sql = "insert into TaskInfo(TaskInfoId,TaskNumber,TaskName,WorkstationNumber,WorkstationName,SchedulingQuantity,ProducedQuantity,ProductionStartTime,ProductionDuration,EstimatedCompletionTime,DisplayColor,TaskInfowjId,IsDelete) values(@TaskInfoId,@TaskNumber,@TaskName,@WorkstationNumber,@WorkstationName,@SchedulingQuantity,@ProducedQuantity,@ProductionStartTime,@ProductionDuration,@EstimatedCompletionTime,@DisplayColor,@TaskInfowjId,@IsDelete)";
                await accreop.Insert(model, sql);
                return result;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                var endTime = System.DateTime.Now;

                var durationInDays = (endTime - startTime).Days;
                nlogs.GetNlogs(
                    request.TaskName ?? "Unknow", "仓库添加", "False", durationInDays, "异常信息"
                    );
            }
        }
    }
}
